<?php
namespace App\Http\Controllers\Front;

use App\Service\Front\CaseService;
use Illuminate\Http\Request;
use ZipArchive as Zip;

class CaseController extends BaseController
{
    //原创案例-导览

    public function __construct(CaseService $caseService)
    {
        $this->db = $caseService;
    }

    //选项分类
    public function getCateList(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        $pid = $request->post('pid', 0);
        $res = $this->db->getCateList($pid);
        return $this->toJson(0, '', $res);
    }

    //列表
    public function getIndex(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        $cateid = $request->get('cate_id', 0);
        $pages['start'] = $request->get('page', 1);
        $pages['limit'] = $request->get('size', 10);
        $pages['start'] = $pages['start'] ? $pages['start'] : 1;
        $pages['limit'] = $pages['limit'] ? $pages['limit'] : 10;
        $res = $this->db->getIndex($cateid, $pages);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //详情
    public function getOne(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        $token = $request->post('token', '');
        $uid = $this->db->uidByToken($token);
//        if (!$uid) {
//            return $this->toJson(-2, '未登录');
//        }
        $id = $request->post('id', 0);
        $res = $this->db->getOne($id, $uid);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

//    //添加
//    public function add(Request $request)
//    {
//        header("Access-Control-Allow-Origin: *");
//        $token = $request->post('token', '');
//        $pas['cid'] = $this->db->cidByToken($token);
//        $pas['title'] = $request->post('title', '');
//        $pas['cate_id'] = $request->post('cate_id', 0);
//        $pas['address'] = $request->post('address', '');
//        $pas['buyer_name'] = $request->post('buyer_name', '');
//        $pas['designer_name'] = $request->post('designer_name', '');
//        $pas['item_area'] = $request->post('item_area', 0);
//        $pas['main_material'] = $request->post('main_material', '');
//        $pas['item_finish_time'] = $request->post('item_finish_time', '');
//        $pas['thumb'] = $request->post('thumb', '');
//        $pas['item_detail'] = $request->post('item_detail', '');
//        if (!$pas['cid']) {
//            return $this->toJson(-2, '你的企业身份无效');
//        }
//        if (!$pas['title']) {
//            return $this->toJson(-2, '项目名称必须的');
//        }
//        $res = $this->db->add($pas);
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        return $this->toJson();
//    }

    //相关推荐
    public function getRecommendList(Request $request)
    {
        $pages['start'] = $request->get('page', 1);
        $pages['limit'] = $request->get('size', 14);
        $pages['start'] = $pages['start'] ? $pages['start'] : 1;
        $pages['limit'] = $pages['limit'] ? $pages['limit'] : 14;
        $cate_id = $request->post('cate_id', 0);
        $res = $this->db->getRecommendList($cate_id, $pages);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //点赞设置
    public function setLike(Request $request)
    {
        $token = $request->post('token', '');
        $case_id = $request->post('case_id', 0);
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        $res = $this->db->setLike($uid, $case_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //关注设置
    public function setFollow(Request $request)
    {
        $token = $request->post('token', '');
        $case_id = $request->post('case_id', 0);
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        $res = $this->db->setFollow($uid, $case_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //收藏设置
    public function setCollect(Request $request)
    {
        $token = $request->post('token', '');
        $case_id = $request->post('case_id', 0);
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        $res = $this->db->setCollect($uid, $case_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //转发设置
    public function setForward(Request $request)
    {
        $token = $request->post('token', '');
        $case_id = $request->post('case_id', 0);
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        $res = $this->db->setForward($uid, $case_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //举报
    public function setJubao(Request $request)
    {
        $token = $request->post('token', '');
        $case_id = $request->post('case_id', 0);
        $cnt = $request->post('remark', '');
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        $res = $this->db->setJubao($uid, $case_id, $cnt);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //在线咨询
    public function onlineAdd(Request $request)
    {
        $token = $request->post('token', '');
        $case_id = $request->post('case_id', 0);
        $cnt = $request->post('detail', '');
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        if (!$cnt) {
            return $this->toJson(-2, '咨询内容必须的');
        }
        $res = $this->db->onlineAdd($uid, $case_id, $cnt);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //打包
    public function zip(Request $request)
    {
        $token = $request->get('token', '');
        $case_id = $request->get('case_id', 0);
        $uid = $this->db->uidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        if (!$case_id) {
            return $this->toJson(-2, '案例必须的');
        }
        $res = $this->db->getOne($case_id, $uid);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $ary = $res['data'];
        $root_path = env('ROOT_PATH');
        $prefix = 'zip';
        $dirname = date('YmdHis', time());
        $fpath = $prefix.'/'.$dirname;
        if(!file_exists($fpath)){
            mkdir($fpath, 0777);
        }
        $fname = $fpath.'/anli-'.date('Ymd',time()).'.txt';
        file_put_contents($fname, '');
        file_put_contents($fname, '项目名称：'.$ary['title'].PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '项目地址：'.$ary['address'].PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '甲方名称：'.$ary['buyer_name'].PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '设计师/设计师团队名称：'.$ary['designer_name'].PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '项目面积：'.$ary['item_area'].'平方'.PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '主要材料：'.$ary['main_material'].PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '完工时间：'.$ary['item_finish_time'].PHP_EOL, FILE_APPEND);
        file_put_contents($fname, '项目详情：'.$ary['item_detail'].PHP_EOL, FILE_APPEND);
        //拷贝封面图片
        if ($ary['thumb']) {
            $imgs = explode('/', $ary['thumb']);
            $img_name = $fpath.'/'.$imgs[count($imgs) - 1];
            if (substr($ary['thumb'], 0, 4) == 'http' || file_exists($ary['thumb'])) {
                $imgCnt = file_get_contents($ary['thumb']);
                file_put_contents($img_name, $imgCnt);
            }
        }
        //拷贝富文本中的图片
        preg_match_all('/<img[^>]+src="([^"]+)"[^>]*>/i', $ary['item_detail'], $matches);
        if ($alls = $matches[1]) {
            foreach ($alls as $v) {
                $imgs = explode('/', $v);
                $img_name = $fpath.'/'.$imgs[count($imgs) - 1];
                if (substr($v, 0, 4) == 'http' || file_exists($v)) {
                    $imgCnt = file_get_contents($v);
                    file_put_contents($img_name, $imgCnt);
                }
            }
        }
        //压缩
        if (!class_exists('ZipArchive')) {
            return $this->toJson(-2, '压缩程序没有安装');
        }
        $targetDir = $root_path.'/'.$fpath.'.zip';
        $zip = new Zip();
        if (!$zip->open($targetDir, Zip::CREATE | Zip::OVERWRITE)) {
            return $this->toJson(-2, "无法打开压缩包 $targetDir");
        }
        $this->addFileToZip($fpath, $dirname, $zip);
        $zip->close();
        $fpath = env('DOMAIN').'/api/pc/case/down?zipName='.$dirname.'.zip';
        exec("chmod -R 777 ".$root_path.'/zip/*');
        return redirect($fpath);
    }

    /**
     * 压缩目录
     * @param string $path 电脑绝对地址
     * @param string $fpath 项目相对地址
     * @param object $zip 压缩对象
     */
    public function addFileToZip($path, $fpath, $zip)
    {
        $handle = opendir($path);
        while (($fname=readdir($handle)) !== false) {
            if (!in_array($fname, ['.', '..'])) {
                if (is_dir($path.'/'.$fname)) {
                    $this->addFileToZip($path.'/'.$fname, $fpath, $zip);
                } else {
                    $zip->addFile($path.'/'.$fname, $fpath.'/'.$fname);
                }
            }
        }
        @closedir();
    }

    //下载zip
    public function down(Request $request)
    {
        $zipName = $request->get('zipName', '');
        $zipName = 'zip/'.$zipName;
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename=' . basename($zipName));
        header('Content-Length: '. filesize($zipName));
        readfile($zipName);
    }
}